<template>
  <main class="gys-apply">
    <!-- 头部背景 -->
    <div class="apply_headimg">
      <img
        :src="gys_apply_background"   
        mode="scaleToFill"
        alt
      />
    </div>
    <section class="apply_tip">
      欢迎加入
      <span>{{shop_info.title }}</span>，请填写申请信息！
    </section>
    <div class="apply_wrapper">
      
      <div class="addurl_con">
        <ul>
          <!--申请类型-->
          <li
            v-if="enterprise.show == 1 || personal.show == 1"
            class="clearfix"
          >
            <label> <b class="colorRed">*</b>类型</label>
            <div class="w60 fr">
              <van-radio-group v-model="submitFormData.apply_type">
              <div class="fl radioChange">
                <van-radio
                  v-if="enterprise.show == 1"
                  :name="1"
                  icon-size="16px"
                  >企业</van-radio>
                </div>
                <div class="fl  radioChange">
                  <van-radio
                    v-if="personal.show == 1"
                    :name="2"
                    icon-size="16px"
                  >个人</van-radio>
                </div>
              </van-radio-group>
            </div>
          </li>
  
          <!-- 公司名称-->
          <li
            v-if="submitFormData.apply_type == 1 && company_name.show==1"
            class="clearfix"
          >
            <label><b
              v-if="company_name.must==1"
              class="colorRed"
            >*</b>{{company_name.name}}</label>
            <div class="w60 fr">
              <input
                :placeholder="'请填写'+company_name.name"
                value=""
                v-model="submitFormData.company_name"
                class="textw"
                data-require="1"
              >
            </div>
          </li>
          <!-- 营业执照号-->
          <li
            v-if="submitFormData.apply_type == 1 && business_licence_num.show==1"
            class="clearfix"
          >
            <label><b
              v-if="business_licence_num.must==1"
              class="colorRed"
            >*</b>{{business_licence_num.customer_name || business_licence_num.name}}</label>
            <div class="w60 fr">
              <input
                v-if="business_licence_num.customer_name"
                :name="business_licence_num.key"
                :placeholder="'请填写'+business_licence_num.customer_name"
                value=""
                v-model="submitFormData.business_licence_num"
                class="textw"
                data-require="1"
              >
              <input
                v-else
                :name="business_licence_num.key"
                :placeholder="'请填写'+business_licence_num.name"
                value=""
                v-model="submitFormData.business_licence_num"
                class="textw"
                data-require="1"
              >
            </div>
          </li>
          <!-- 上传营业执照-->
          <li
            v-if="submitFormData.apply_type == 1 && business_licence_img.show==1"
            class="clearfix autoHeight"
          >
            <label><b
              v-if="business_licence_img.must==1"
              class="colorRed"
            >*</b>{{business_licence_img.customer_name || business_licence_img.name}}</label>
            
            <div class="w60 fr">
              <!-- TODO 上传营业执照 -->
              <SmallUploadImg ref="smallUploadImgYYZZ" :maxLength="5"></SmallUploadImg>

            </div>
          </li>
          <!-- 身份证号-->
          <li
            v-if="submitFormData.apply_type == 2 && card_no.show==1"
            class="clearfix"
          >
            <label><b
              v-if="card_no.must==1"
              class="colorRed"
            >*</b>{{card_no.name}}</label>
            <div class="w60 fr">
              <input
                :name="card_no.key"
                :placeholder="'请填写'+card_no.name"
                v-model="submitFormData.card_no"
                class="textw"
                data-require="1"
              >
            </div>
          </li>
          <!-- 上传身份证正面-->
          <li
            v-if="submitFormData.apply_type == 2 && card_positive.show==1"
            class="clearfix autoHeight"
          >
            <label><b
              v-if="card_positive.must==1"
              class="colorRed"
            >*</b>{{card_positive.name}}</label>
            
            <div class="w60 fr">
              <!-- TODO 上传身份证正面 -->
              <SmallUploadImg ref="smallUploadImgCardPos" :maxLength="1"></SmallUploadImg>
              <span v-if="card_positive_txt">{{ card_positive_txt }}</span>
            </div>
          </li>
  
          <!-- 上传身份证反面-->
          <li
            v-if="submitFormData.apply_type == 2 && card_opposite.show==1"
            class="clearfix autoHeight"
          >
            <label><b
              v-if="card_opposite.must==1"
              class="colorRed"
            >*</b>{{card_opposite.name}}</label>
            <div class="w60 fr">
              <!-- TODO 上传身份证正面 -->
              <SmallUploadImg ref="smallUploadImgCardOpp" :maxLength="1"></SmallUploadImg>
              <span v-if="card_opposite_txt">{{ card_opposite_txt }}</span>
            </div>
          </li>
  
          
          <!--公共部分-->
          <!--供货类型-->
          <li
            v-if="apply_name.show==1"
            class="clearfix"
          >
            <label><b
              v-if="supply_type.must==1"
              class="colorRed"
            >*</b>{{supply_type.name}}</label>
            <div class="w60 fr">
              <div class="apply-right" @click="showGysPicker=true"><span :class="showGysName ? 'col9':''">{{showGysName ? showGysName:'请选择供货类型'}}</span><img src="https://img.wifenxiao.com/h5-wfx/images/refund/arrow_r.png" alt=""></div>
            </div>
          </li>
          
          <!--申请人-->
          <li
            v-if="apply_name.show==1"
            class="clearfix"
          >
            <label><b
              v-if="apply_name.must==1"
              class="colorRed"
            >*</b>{{apply_name.name}}</label>
            <div class="w60 fr">
              <input
                :name="apply_name.key"
                :placeholder="'请填写'+apply_name.name"
                v-model="submitFormData.apply_name"
                class="textw"
              >
            </div>
          </li>
          
          <!--联系人电话-->
          <li
            v-if="mobile.show==1"
            class="clearfix"
          >
            <label><b
              v-if="mobile.must==1"
              class="colorRed"
            >*</b>{{mobile.name}}</label>
            <div class="w60 fr">
              <input
                :name="mobile.key"
                :placeholder="'请填写'+mobile.name"
                value=""
                v-model="submitFormData.mobile"
                class="textw"
              >
            </div>
          </li>
  
          <!--密码-->
          <li
            class="clearfix"
          >
            <label><b
              class="colorRed"
            >*</b>密码</label>
            <div class="w60 fr">
              <input
                type="password"
                :placeholder="'请填写密码'"
                v-model="submitFormData.password"
                class="textw"
              >
            </div>
          </li>
  
          <!-- 地址信息-->
          <li
            v-if="address.show==1"
            class="clearfix"
          >
            <label><b
              v-if="address.must==1"
              class="colorRed"
            >*</b>{{address.name}}</label>
            <div class="w60 fr">
              <small-area-picker class="area-picker" @procityareaInfo="procityareaInfo"></small-area-picker>
            </div>
          </li>
          
          <!--详细地址-->
          <li
            v-if="address.show==1"
            class="clearfix"
          >
            <label><b
              v-if="address.must==1"
              class="colorRed"
            >*</b>{{address.name}}</label>
            <div class="w60 fr">
              <input
              :placeholder="'请填写'+address.name"
              v-model="submitFormData.address"
              class="textw"
            >
            </div>
          </li>
  
          <!--备注-->
          <li
            v-if="remark.show==1"
            class="clearfix"
          >
            <label><b
              v-if="remark.must==1"
              class="colorRed"
            >*</b>{{remark.name}}</label>
            <div class="w60 fr">
              <input
                :placeholder="'请填写'+remark.name"
                v-model="submitFormData.remark"
                class="textw"
              >
            </div>
          </li>
  
          <!--招商经理ID-->
          <li
            v-if="recommend_id.show==1"
            class="clearfix"
          >
            <label><b
              v-if="recommend_id.must==1"
              class="colorRed"
            >*</b>{{recommend_id.name}}</label>
            <div class="w60 fr">
              <input
                :placeholder="'请填写'+recommend_id.name"
                v-model="submitFormData.recommend_id"
                class="textw"
              >
            </div>
          </li>

          <!-- 备注项 -->
          <li v-if="item.display" v-for="item in extra_config" :key="item.key" class="clearfix">
            <label><b v-if="item.must==1" class="colorRed">* </b>{{item.name}}</label>
            <div class="w60 fr">
              <input :name="item.key" :placeholder="'请填写'+item.name" v-model="item.value" class="textw">
            </div>
          </li>

          <!-- 自定义上传图片 -->
          <li
            v-if="upload_img.show==1"
            class="clearfix autoHeight"
          >
            <label><b
              v-if="upload_img.must==1"
              class="colorRed"
            >*</b>上传图片</label>
            
            <div class="w60 fr">
              <SmallUploadImg ref="smallUploadImgCustom" :maxLength="9"></SmallUploadImg>
            </div>
          </li>
        </ul>
  
        <section class="">
          <div class="agreenment">
            <div v-if="gys_apply_agreement || contract_documents" class="agreenment-inline">
              <van-checkbox icon-size="14px" shape="square" v-model="submitFormData.need_apply_agreement">我已阅读并同意</van-checkbox>
            </div>
            <span
              v-if="gys_apply_agreement"
              @click="agreementContent = !agreementContent"
              class="colorBlue"
            >《{{ ftitle_supplier }}申请协议》</span>
            <a
              v-if="contract_documents"
              class="contract_documents j-download"
              @click="downloadDoc(contract_documents)"
              download="代理商合同"><span class="colorBlue">《{{ftitle_supplier}}合同》</span></a>
  
            <section v-if="agreementContent && gys_apply_agreement" class="agreenment-txt">
              <section v-html="gys_apply_agreement"></section>
            </section>
          </div>
        </section>
  
  
        <section
          class="mlogin_but">
          <a
            class="J-addApply"
            href="javascript:;"
            @click="handleClickApply"
        >同意协议并申请</a></section>
        
      </div>
    </div>
    <van-popup v-model="showGysPicker" round position="bottom">
      <van-picker
        show-toolbar
        :columns="gysColumns"
        @cancel="showGysPicker = false"
        @confirm="onConfirmGys"
      />
    </van-popup>
    <map-area :visible.sync="showAreaPop" @onSelect="handleConfirm"></map-area>
    <share-btn v-if="application_poster_switch" type="5"></share-btn>
  </main>
</template>

<script>
/*
 * @Author: cd@360shop.cn
 * @Date: 2019-09-26 16:48:09
 * @Last Modified by: zhangmeng
 * @Last Modified time: 2020-07-01 16:36:59
 */
import mapArea from '@/components/mapArea'
import shareBtn from '../../component/shareBtn'
import SmallUploadImg from '@/components/SmallUploadImg'
import SmallAreaPicker from '@/components/smallAreaPicker/smallareapicker.vue'
import { gysdhsRequest, applySupplier } from '@/api/identityApplication/identityApplication'
import { uploadImgs } from '@/api/community/article'
import { openPage } from '@/utils/utils'
import Vue from 'vue'
import { RadioGroup, Radio, DropdownMenu, DropdownItem, Checkbox, CheckboxGroup, Uploader, Picker, Popup } from 'vant'
import 'vant/lib/index.css'
Vue.use(RadioGroup)
Vue.use(Radio)
Vue.use(DropdownMenu)
Vue.use(DropdownItem)
Vue.use(Checkbox)
Vue.use(CheckboxGroup)
Vue.use(Uploader)
Vue.use(Picker)
Vue.use(Popup)
export default Vue.extend({
  name: 'common',
  components: {
    mapArea,
    SmallUploadImg,
    SmallAreaPicker,
    shareBtn
  },
  data() {
    return {
      showAreaPop: false,
      areaBtnText: '点击选择地址',
      fileList: [],
      fileListImg: [],
      fileListCustom: [], // 自定义上传图片
      fileListCustomImg: [],
      showGysPicker: false,
      gysColumns: [],
      showGysName: '',
      submitFormData: {
        apply_type: 1,
        card_no: '',
        card_positive: '',
        card_opposite: '',
        company_name: '',
        business_licence_num: '',
        business_licence_img: '',
        supply_type: 0,
        apply_name: '',
        mobile: '',
        password: '',
        address: '',
        remark: '',
        recommend_id: '',
        need_apply_agreement: 1,
        file_list_custom_img: ''
      }, // 默认为空
      agreementContent: true, // 协议文本的显示隐藏
      ftitle_supplier: '',
      supply_title: '',
      chonse_type: '',
      applyInfo: '',
      gys_apply_background: '',
      contract_documents: '',
      need_gys_apply_agreement: '',
      gys_apply_config: [],
      gys_apply_agreement: '',
      shop_info: {},
      //
      // 填写项 start
      enterprise: {}, // 企业
      company_name: {}, // 公司名称
      business_licence_num: {}, // 营业执照
      business_licence_img: {}, // 上传营业执照
      personal: {},
      card_no: {}, // 身份证号
      card_positive: {}, // 身份证正面
      card_opposite: {}, // 身份证反面
      supply_type: {}, // 供货类型
      apply_name: {}, // 申请人
      mobile: {}, // 手机号
      address: {}, // 地址
      remark: {}, // 备注
      recommend_id: {}, // 招商经理
      extra_config: '', // 备注项
      upload_img: {}, // 上传图片
      // 填写项 end
      // 上传提示信息
      business_licence_txt: '',
      card_positive_txt: '',
      card_opposite_txt: '',
      supplyTypeList: [],
      application_poster_switch: 0
    }
  },
  methods: {
    onConfirmGys(val, idx) {
      this.showGysName = val
      this.submitFormData.supply_type = this.supplyTypeList[idx].type_id
      this.showGysPicker = false
    },
    /**
     * 获取供应商申请默认配置
     */
    gysdhsRequestFun() {
      gysdhsRequest().then(res => {
        if (res.status == 1) {
          this.ftitle_supplier = res.data.ftitle_supplier
          this.supply_title = res.data.supply_title
          this.chonse_type = res.data.chonse_type
          this.applyInfo = res.data.applyInfo
          this.gys_apply_background = res.data.gys_apply_background
          this.contract_documents = res.data.contract_documents
          // this.gys_apply_config = res.data.gys_apply_config
          this.gys_apply_agreement = this.getHtml(res.data.gys_apply_agreement)
          this.supplyTypeList = res.data.supply_type || []

          const gysLevelList = []
          this.supplyTypeList.map(item => {
            gysLevelList.push(item.type_name)
          })

          this.gysColumns = gysLevelList
          this.shop_info = res.data.shop_info
          // 填写部分
          this.enterprise = res.data.gys_apply_config.enterprise
          this.company_name = res.data.gys_apply_config.company_name
          this.business_licence_num = res.data.gys_apply_config.business_licence_num
          this.business_licence_img = res.data.gys_apply_config.business_licence_img
          this.personal = res.data.gys_apply_config.personal
          this.card_no = res.data.gys_apply_config.card_no
          this.card_positive = res.data.gys_apply_config.card_positive
          this.card_opposite = res.data.gys_apply_config.card_opposite
          this.supply_type = res.data.gys_apply_config.supply_type
          this.apply_name = res.data.gys_apply_config.apply_name
          this.mobile = res.data.gys_apply_config.mobile
          this.address = res.data.gys_apply_config.address
          this.remark = res.data.gys_apply_config.remark
          this.recommend_id = res.data.gys_apply_config.recommend_id
          this.application_poster_switch = res.data.application_poster_switch
          const newArr = []
          const extra_config = res.data.extra_config
          if (extra_config) {
            Object.keys(extra_config).forEach((key) => {
              extra_config[key].key = key
              extra_config[key].value = ''
              newArr.push(extra_config[key])
            })
          }
          this.extra_config = newArr
          this.upload_img = res.data.gys_apply_config.upload_img
          // 默认类型选中
          if (this.enterprise.show !== 1) this.submitFormData.apply_type = 2
            wx.setNavigationBarTitle({
              title: this.supply_title 
            })
        } else {
          this.$Error(res.msg)
          if (res.jump_url) {
            setTimeout(() => {
              openPage(res.jump_url)
            }, 1000)
          }
        }
      })
    },
    /**
     * v-html无法转义解决办法
     */
    getHtml(desc) {
      var temp = document.createElement('div')
      temp.innerHTML = desc
      var output = temp.innerText || temp.textContent
      temp = null
      return output
    },
    /**
     * 申请按钮
     */
    handleClickApply() {
      this.$loadingWrap.show()
      setTimeout(() => {
        this.$loadingWrap.close()
      }, 10000)
      // TODO 上传
      let business_licence_img_arr = []
      let custom_img_arr = []
        business_licence_img_arr=this.$refs.smallUploadImgYYZZ?this.$refs.smallUploadImgYYZZ.imgList:[]
        // //身份证正面
        this.submitFormData.card_positive = this.$refs.smallUploadImgCardPos?this.$refs.smallUploadImgCardPos.imgList[0]:''
        // //身份证反面
        this.submitFormData.card_opposite = this.$refs.smallUploadImgCardOpp?this.$refs.smallUploadImgCardOpp.imgList[0]:''   
        custom_img_arr = this.$refs.smallUploadImgCustom?this.$refs.smallUploadImgCustom.imgList:[]  
      
      const submitFormData = Object.assign({}, this.submitFormData, true)
      submitFormData.upload_imgs = custom_img_arr.join(',')
      submitFormData.business_licence_img = business_licence_img_arr.join(',')
      if (!submitFormData.need_apply_agreement) submitFormData.need_apply_agreement = 0
      const extra_config = this.extra_config
      extra_config.forEach(item => {
        submitFormData[item.key] = item.value
      })
      applySupplier(submitFormData).then(res => {
        this.$loadingWrap.close()
        if (res.status == 1) {
          // TODO 提示信息由后端返回
          this.$Error(res.msg)
          setTimeout(() => {
            openPage(res.jump_url)
          }, 1000)
        } else {
          this.$Error(res.msg)
        }
      })
    },
    // 小程序选择省市区
    procityareaInfo(val) {
      this.handleConfirm(val)
    },

    // 点击调用地址选择
    selectAddress() {
      this.showAreaPop = true
    },
    // 确认
    handleConfirm(val) {
      if (!val.province_id || !val.city_id) {
        this.$Error('请选择完整的省市县')
      } else {
        this.showAreaPop = false
        this.areaBtnText = val.province_name + ' ' + val.city_name + ' ' + val.area_name
        this.submitFormData.province_id = val.province_id
        this.submitFormData.city_id = val.city_id
        this.submitFormData.area_id = val.area_id
      }
    },
    /**
     * 上传营业执照
     */
    uploadBusinessLicence(file) {
      this.uploadImgsFn(file, 'businessLicence')
    },
    /**
     * 删除营业执照
     */
    deleteEvent() {
      this.fileListImg = this.fileList
    },
    /**
     * 上传身份证正面
     */
    uploadCardPositive(file) {
      this.uploadImgsFn(file, 'cardPositive')
    },
    /**
     * 上传省份证反面
     */
    uploadCardOpposite(file) {
      this.uploadImgsFn(file, 'cardOpposite')
    },

     /**
     * 自定义上传图片
     */
    uploadCustomImg(file) {
      this.uploadImgsFn(file, 'customImg')
    },
    /**
     * 删除自定义上传图片
     */
    deleteCustomImg() {
      this.fileListCustomImg = this.fileListCustom
    },
    /**
     * 上传图片
     */
    uploadImgsFn(file, type) {
      this.$loadingWrap.show()
      setTimeout(() => {
        this.$loadingWrap.close()
      }, 10000)
      const form = new FormData()
      form.append('file', file.file)
      uploadImgs(form).then(res => {
        this.$loadingWrap.close()
        if (res.status == 1) {
          if (type == 'businessLicence') {
            this.fileList = []
            this.business_licence_img.value = res.data.pic_url
            const obj = {
              url: res.data.pic_url,
              isImage: true
            }
            this.fileListImg.push(obj)
            this.fileList = this.fileListImg
            this.business_licence_txt = '上传成功'
            } else if (type == 'customImg') {
            this.fileListCustom = []
            this.upload_img.value = res.data.pic_url
            const customObj = {
              url: res.data.pic_url,
              isImage: true
            }
            this.fileListCustomImg.push(customObj)
            this.fileListCustom = this.fileListCustomImg
          } else if (type == 'cardPositive') {
            this.submitFormData.card_positive = res.data.pic_url
            this.card_positive_txt = '上传成功'
          } else if (type == 'cardOpposite') {
            this.submitFormData.card_opposite = res.data.pic_url
            this.card_opposite_txt = '上传成功'
          }
        } else {
          if (type == 'businessLicence') {
            this.submitFormData.business_licence_img = ''
            this.business_licence_txt = '上传失败'
          } else if (type == 'cardPositive') {
            this.submitFormData.card_positive = ''
            this.card_positive_txt = '上传失败'
          } else if (type == 'cardOpposite') {
            this.submitFormData.card_opposite = ''
            this.card_opposite_txt = '上传失败'
          }
        }
      })
    },
    // 下载合同
    downloadDoc(url){
        wx.downloadFile({
          url: url,
          success: function (res) {
            let fileType = url.substring(url.lastIndexOf(".")+1);
            if(fileType.indexOf('@') !== -1) {
              fileType = fileType.substring(0, fileType.indexOf('@'));
            }
            const tempPath = res.tempFilePath;
            const imgType = "|png|gif|jpg|jpeg|";
            if(imgType.indexOf(fileType)>0) {
              wx.saveImageToPhotosAlbum({      
                filePath: tempPath,
                success(res) {
                  // console.log('保存成功');
                  wx.showToast({
                    title: '保存成功',
                    icon: 'success',
                    duration: 2000
                  })
                },
                fail: function(err) {
                  if(err.errMsg === "saveImageToPhotosAlbum:fail:auth denied" || err.errMsg === "saveImageToPhotosAlbum:fail auth deny" || err.errMsg === "saveImageToPhotosAlbum:fail authorize no response") {
                    wx.showModal({
                      title: '提示',
                      content: '需要您授权保存相册',
                      showCancel: false,
                      success: modalSuccess => {
                        wx.openSetting({
                          success(settingdata) {
                            if (settingdata.authSetting['scope.writePhotosAlbum']) {
                              // console.log('获取权限成功，给出再次点击图片保存到相册的提示。')
                            }else {
                              // console.log('获取权限失败，给出不给权限就无法正常使用的提示')
                            }
                          }
                        })
                      }
                    })
                  }
                }
              })
            } else {
              wx.saveFile({
                tempFilePath: tempPath, 
                success:function(res){
                  const savePath = res.savedFilePath;
                  wx.openDocument({
                    filePath: savePath,
                    fileType: fileType,
                    showMenu: true,
                    success :function(res){
                      // console.log('打开文档成功')
                    },
                  });
                },
                fail: function (err) {
                  // console.log('保存失败：', err)
                }
              })
            }
          }
        })

    },
  },
  created() {
    this.gysdhsRequestFun()
  }
})
</script>

<style lang="scss">
  @import "src/styles/identityApplication/index.scss";
  .gys-apply{
    .van-dropdown-menu__item{
      justify-content: left!important;
      .van-dropdown-menu__title{
        font-size: 24px!important;
      }
    }
    .van-checkbox__label {
      color: #666;
    }
    .van-radio__icon--checked .van-icon,.van-checkbox__icon--checked .van-icon {
      background-color: #FE1B49;
      border-color: #FE1B49;
    }

    .van-dropdown-menu__bar {
      background-color: none;
      box-shadow: none;
    }

    .van-dropdown-item {
      width: calc(100% - 50px);
      left: 25px;
    }
    .van-radio__label {
      font-weight: 500;
    }
    .van-radio-group {
      display: inline-block;
    }

    .apply_headimg {
        width: 100%;
        height: 250px;
        img {
          width: 100%;
          height: 100%;
        }
      }
    .apply_wrapper {
      width: calc(100% - 50px);
      margin: 0px 25px;
      padding: 0 25px;
      box-sizing: border-box;
      border-radius: 20px;
      background-color: #fff;
      overflow: hidden;
    }
    .autoHeight{
      height: auto!important;
      .van-uploader{
        display: block!important;
        margin-top: 10px;
      }
    }
    .area-picker{
      padding:32px 30px;
      color:#666;
    }
  }
</style>
